package com.koron.css2.meterService.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BaseReceiptAccessoryMapper;
import com.koron.css2.meterService.bean.MsInfoPlanBean;
import com.koron.css2.meterService.bean.MsInfoPlanDetailBean;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.meterService.mapper.MsInfoPlanDetailMapper;
import com.koron.css2.meterService.mapper.MsInfoPlanMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import com.koron.util.ValidationKey;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.*;

/**
 * 水表入库登记
 * @author 周利斌
 *
 */
public class MsStorageAdd implements ServerInterface{

	@Override
    @ValidationKey(clazz = MsInfoPlanBean.class,method = "insert")
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		
		@SuppressWarnings("rawtypes")
		MessageBean<Map> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "添加成功", Map.class);
		try {
			MsInfoPlanBean msInfoPlan = JsonUtils.objectToPojo(req.getData(), MsInfoPlanBean.class);
			MsInfoPlanDetailMapper mapper = factory.getMapper(MsInfoPlanDetailMapper.class);	
			MsInfoPlanMapper msInfoPlanMapper = factory.getMapper(MsInfoPlanMapper.class);
			MsInfoMapper msInfoMapper = factory.getMapper(MsInfoMapper.class);
			List<MsInfoPlanDetailBean> msInfoPlanDetails = msInfoPlan.getMsInfoPlanDetail();
			msInfoPlan.setCreateName(userInfo.getUserInfo().getName());
			String receiptId = Tools.getObjectId();
			msInfoPlan.setId(receiptId);
			msInfoPlan.setStroageCount(msInfoPlanDetails.size());
			if(msInfoPlan.getMaxValue() == null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "满码值不能为空", Void.class);
			}
			if(msInfoPlanDetails == null || msInfoPlanDetails.size() <= 0) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "明细不能为空", Void.class);
			}
			MsInfoPlanDetailBean repeat = imeiIsRepeat(msInfoPlanDetails);
			if(repeat != null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表明细存在重复的IMEI号：" + repeat.getImei(), void.class);
			};
			repeat = imsiIsRepeat(msInfoPlanDetails);
			if(repeat != null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表明细存在重复的IMSI号：" + repeat.getImsi(), void.class);
			};
			for(MsInfoPlanDetailBean msInfoPlanDetail : msInfoPlanDetails) {
				if(StringUtils.isBlank(msInfoPlanDetail.getFactoryNo())) {
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "出厂编号不能为空", Void.class);
				}
				if(StringUtils.isBlank(msInfoPlan.getMeterBore()) && StringUtils.isBlank(msInfoPlanDetail.getMeterBore())) {
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表口径不能为空", Void.class);
				}
				if(StringUtils.isBlank(msInfoPlan.getMeterModel()) && StringUtils.isBlank(msInfoPlanDetail.getMeterModel())) {
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表型号不能为空", Void.class);
				}
				MsInfoDto msInfoDto = msInfoMapper.getMsInfoByNo(msInfoPlanDetail.getMeterNo());
				MsInfoPlanDetailBean detail = mapper.selectByFactoryNo(msInfoPlanDetail.getFactoryNo());
				if(detail != null) {
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "存在相同的水表表身号(" + msInfoPlanDetail.getFactoryNo() + ")", Void.class);
				}
				if(msInfoDto != null) {
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "存在相同的水表编号(" + msInfoDto.getMeterNo() + ")", Void.class);
				}
				if(StringUtils.isNotEmpty(msInfoPlanDetail.getImei())){ // 判断是否存在相同的IMEI 号
					int iCount = mapper.countByImei(msInfoPlanDetail.getImei());
					if (iCount > 0){
						return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表库中存在相同的水表IMEI号(" + msInfoPlanDetail.getImei() + ")", Void.class);
					}
				}
				if(StringUtils.isNotEmpty(msInfoPlanDetail.getImsi())){ // 判断是否存在相同的IMSI号
					int iCount = mapper.countByImei(msInfoPlanDetail.getImsi());
					if (iCount > 0){
						return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表库中存在相同的水表IMSI号(" + msInfoPlanDetail.getImsi() + ")", Void.class);
					}
				}
				msInfoPlanDetail.setCreateName(userInfo.getUserInfo().getName());
				msInfoPlanDetail.setId(Tools.getObjectId());
				msInfoPlanDetail.setReceiptId(receiptId);
				if(msInfoPlanDetail.getMeterNo() == null || "".equals(msInfoPlanDetail.getMeterNo())) {
					msInfoPlanDetail.setMeterNo(Tools.getBillNo(factory, "METER_NO", userInfo.getCurWaterCode()));  //水表编号
				}
				if(StringUtils.isNotEmpty(msInfoPlanDetail.getImei())) {
					msInfoPlanDetail.setImei(msInfoPlanDetail.getImei().trim()); // 去除空格
				}
				if(StringUtils.isNotEmpty(msInfoPlanDetail.getImsi())) {
					msInfoPlanDetail.setImsi(msInfoPlanDetail.getImsi().trim()); // 去除空格
				}
				msInfoPlanDetail.setFactoryNo(msInfoPlanDetail.getFactoryNo().trim()); // 去除空格
				mapper.addMsInfoPlanDetail(msInfoPlanDetail);
			}
			msInfoPlan.setBillDate(new Date());
			msInfoPlan.setBillNo(Tools.getBillNo(factory, "ms_in_plan")); //单据编号
			msInfoPlanMapper.addMsInfoPlan(msInfoPlan);
			Map<String, String> data = new HashMap<String, String>();
			data.put("id", receiptId);
			info.setData(data);
			BaseReceiptAccessoryMapper accessoryMapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
			if(!StringUtils.isBlank(msInfoPlan.getTempId()))		//修改附件ID
				accessoryMapper.updateAccessoryReceiptId(receiptId, msInfoPlan.getTempId());
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("添加失败");
			logger.error(e.getMessage(), e);
		}
		return info;
	}

	private MsInfoPlanDetailBean imeiIsRepeat(List<MsInfoPlanDetailBean> list) {
		for (int i = 0; i < list.size(); i++){
			MsInfoPlanDetailBean msInfo1 = list.get(i);
			if (StringUtils.isBlank(msInfo1.getImei()))continue;
			for (int j = i + 1; j < list.size(); j++){
				MsInfoPlanDetailBean msInfo2 = list.get(j);
				if (StringUtils.isBlank(msInfo2.getImei()))continue;
				if (Objects.equals(msInfo1.getImei(), msInfo2.getImei())){
					return msInfo1;
				}
			}
		}
		return null;
	}

	private MsInfoPlanDetailBean imsiIsRepeat(List<MsInfoPlanDetailBean> list) {
		for (int i = 0; i < list.size(); i++){
			MsInfoPlanDetailBean msInfo1 = list.get(i);
			if (StringUtils.isBlank(msInfo1.getImsi()))continue;
			for (int j = i + 1; j < list.size(); j++){
				MsInfoPlanDetailBean msInfo2 = list.get(j);
				if (StringUtils.isBlank(msInfo2.getImsi()))continue;
				if (Objects.equals(msInfo1.getImsi(), msInfo2.getImsi())){
					return msInfo1;
				}
			}
		}
		return null;
	}

}
